import json
import os
from typing import Optional

__file_name = ".dayu"
__expired_timeout = 3600 * 4


class DyToken:
    """token操作"""

    @property
    def token_file(self) -> str:
        return ".dayu"

    @property
    def token_expired_timeout(self) -> int:
        return 3600 * 4

    def get(self) -> Optional[dict]:
        if self.__check_file_expired():
            return None

        value = self.__read_token()
        if len(value) > 0:
            return json.loads(value)

        return None

    def set(self, token: dict):
        if token:
            self.__save_token(json.dumps(token))

    def __token_filepath(self):
        """Token文件保存路径"""
        user_home_dir = os.path.expanduser("~")
        file_path = os.path.join(user_home_dir, self.token_file)

        return file_path

    def __save_token(self, accessToken: str) -> None:
        """保存token"""
        file_path = self.__token_filepath()
        with open(file_path, "w") as f:
            f.write(accessToken)

    def __read_token(self):
        """读取token"""
        file_path = self.__token_filepath()
        if not os.path.exists(file_path):
            return ""

        with open(file_path, "r") as f:
            value = f.read()
            return value

    def __check_file_expired(self):
        # 检查文件是否存在
        file_path = self.__token_filepath()
        if not os.path.exists(file_path) or not os.path.isfile(file_path):
            return True

        # last_modified_timestamp = os.path.getmtime(file_path)
        # current_timestamp = time.time()
        # time_difference = int(current_timestamp - last_modified_timestamp)
        # # 如果文件的最后修改时间超过指定时间，则过期
        # if time_difference > self.token_expired_timeout:
        #     # os.remove(file_path)
        #     return True

        return False
